﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SimpComm
{

    /// <summary>
    /// 此类用于动态排序 (蓝伟航 2012年8月31号)
    /// </summary>
    public class DynamicOrderby
    {
        private Dictionary<string, string> _orderbys;

        /// <summary>
        /// 初始函数
        /// </summary>
        /// <param name="ls">字段,排序方式,</param>
        /// <returns></returns>
        public DynamicOrderby(params string[] ls)
        {
            _orderbys = new Dictionary<string, string>();
            Add(ls);
        }


        /// <summary>
        /// 静态方法,创建一个实例,懒人专用
        /// </summary>
        /// <param name="ls">字段,排序方式,</param>
        /// <returns></returns>
        public static DynamicOrderby Creat(params string[] ls)
        {
            return new DynamicOrderby(ls);
        }

        /// <summary>
        /// 添加字段
        /// </summary>
        /// <param name="ls">字段,排序方式,</param>
        public void Add(params string[] ls)
        {
            for (int i = 1; i < ls.Length; i = i + 2)
            {
                string temp = "asc";
                if (ls[i] == "desc"
                    || ls[i] == "DESC"
                    || ls[i] == "Desc")
                    temp = "desc";
                if (!string.IsNullOrWhiteSpace(ls[i - 1]))
                    _orderbys.Add(ls[i - 1], temp);
            }
        }

        /// <summary>
        /// 转换成为排序字符串
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();
            foreach (var orderby in _orderbys)
            {
                sb.Append(orderby.Key + " " + orderby.Value + ",");
            }
            if (sb.Length > 0)
                return sb.ToString(0, sb.Length - 1);//删除最后逗号
            return null;
        }

        /// <summary>
        /// 判断排序传入的值是否正确
        /// </summary>
        public bool IsRight
        {
            get
            {
                return _orderbys != null && _orderbys.Count > 0;
            }
        }
    }
}
